package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ly
 * @Date: 2021/08/01/14:24
 * @Description:
 */

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //查询好友的动态，实际上就是查询时间线表

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line" + userId);

        if (CollectionUtils.isEmpty(timeLineList)) {
            //没有查询到数据
            return pageInfo;
        }

   /*     //获取到好友所有的发布id（动态id）
        List<ObjectId> ids=new ArrayList<>();
        for (TimeLine timeLine : timeLineList) {
            ids.add(timeLine.getPublishId());
        }*/


        //获取时间线表中所有的发布id
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        //根据动态id查询动态列表
        Query queryPublish = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishes = mongoTemplate.find(queryPublish, Publish.class);

        pageInfo.setRecords(publishes);
        return pageInfo;
    }


    /**
     * 发布动态
     *
     * @param publish
     * @return 发布成功返回动态id
     */
    @Override
    public String savePublish(Publish publish) {
        //对publish对象校验
        if (!ObjectUtil.isAllEmpty(publish.getId(), publish.getText())) {

            //发布失败
            return null;
        }

        try {
            //设置主键id
            publish.setId(ObjectId.get());

            publish.setPid(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            //写入到publish表中
            mongoTemplate.save(publish);

            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());

            mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            //写入好友的时间线表（异步写入）
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
















    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Publish.class);
    }


    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断该用户是否已经点赞，如果已经点赞就直接返回
        if (queryUserIsLike(userId, publishId)) {
            return false;
        }

        //如果没有点赞，保存Comment数据
        //修改点赞数
        boolean result = saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            //点赞失败
            return false;
        }

        //修改redis中的点赞数以及是否点赞
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }


    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户是否已经点赞，如果没有点赞就返回

        if (!queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除评论数据
        boolean result = removeComment(userId, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }
        //修改Redis中的数据
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }


    /**
     * 查询点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        //从Redis中命中查询，如果命中直接返回即可
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }
        //查询Mongodb
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        //写入Redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    /**
     * 查询数量
     *
     * @param publishId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);

    }


    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where(publishId).is(new ObjectId(publishId)).
                and("userId").is(userId).
                and("CommentType").is(CommentType.LIKE));
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }
        //写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }


    /*
    * 喜欢
    * */
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //查询该用户是否已经喜欢
        if (queryUserIsLove(userId,publishId)){
            //喜欢过了直接返回
            return false;
        }
        //喜欢
        boolean result = saveComment(userId, publishId,CommentType.LOVE,null);
        if (!result){
            return  false;
        }
        //喜欢成功后，修改Redis中的总的喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,1);

        //标记用户已经喜欢
        hashKey = getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().put(redisKey,hashKey,"1");

        return true;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
       return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }


    /*
     * 取消喜欢
     * */
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //先查询用户是否喜欢
        if (!queryUserIsLove(userId, publishId)){
            //不喜欢直接返回
            return false;
        }

        boolean result = removeComment(userId, publishId, CommentType.LOVE);
        if (!result){
            //取消喜欢失败
            return false;
        }
        //删除redis中的记录
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey =  getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().delete(redisKey,hashKey);
        redisTemplate.opsForHash().increment(redisKey,CommentType.LOVE.toString(),-1);
        /*String redisKey = getCommentUserLoveRedisKey(userId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);*/
        return true;
    }


    /*
     * 查询喜欢数
     * */
    @Override
    public Long queryLoveCount(String publishId) {
        //首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)){
            return Convert.toLong(value);
        }

        //查询count
        Long count = queryCommentCount(publishId, CommentType.LOVE);

        //存储到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,count);
        return count;
    }


    /*
     * 查询用户是否喜欢
     * */
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)){
            return StrUtil.equals(Convert.toStr(value),"1");
        }

        //查询mongodb
        Query query=Query.query(Criteria.where("publishId").is(publishId).
                                          and("userId").is(userId).
                                          and("commentType").is(CommentType.LOVE.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        if (count==0){
            //不喜欢
            return false;
        }
        //标记用户已经喜欢
        redisTemplate.opsForHash().put(redisKey,hashKey,"1");
        return true;
    }



    /**
     * 保存Comment
     *
     * @return
     */
    private boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            // 评论类型
            comment.setCommentType(commentType.getType());
            // 内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            Publish publish = this.queryPublishById(publishId);
            //TODO 其他评论对象，暂不处理
            comment.setPublishUserId(publish.getUserId());

            this.mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }


    private boolean removeComment(Long userId, String publishId, CommentType commentType) {

        Query query=Query.query(Criteria.where("userId").is(userId).
                                          and("publishId").is(publishId).
                                          and("CommentType").is(commentType.getType()));
      return mongoTemplate.remove(query, Comment.class).getDeletedCount()>0;
    }

}

